package com.seo.service.deduc.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.seo.mapper.transaction.TransactionMapperM;
import com.seo.mapper.user.account.AccountMapper;
import com.seo.pojo.ReturnBody;
import com.seo.service.user.sdk.UserService;
import com.seo.utils.CustomUtil;
import com.seo.utils.DataUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("deducService")
public class DeducServiceImpl {

	@Autowired
	private TransactionMapperM transactionMapperM;

	@Autowired
	private AccountMapper accountMapper;

	@Autowired
	private UserService userService;

	public ReturnBody saveDeducDetail(String tradeId, Map<String, Object> params) {
		ReturnBody rb = ReturnBody.init();
		try {
			log.info("[{}]-查看用户是否存在", tradeId);
			if (!params.containsKey("userName")) {
				log.error("[{}]-用户名不能为空", tradeId);
				return rb.rollback("用户不能为空");
			}

			String userName = (String) params.get("userName");
			rb.run(userService.getUserByName(userName));
			if (!rb.isSuccess()) {
				return rb;
			}
			Integer userId = rb.get("userId", Integer.class);

			Map<String, Object> user = rb.get("user", String.class, Object.class);

			int parentId = (int) user.get("parentId");
			
			if(params.containsKey("parentId")) {
				int pId = (int)params.get("parentId");
				if(pId != parentId) {
					log.error("[{}]-只能选择自己的下级", tradeId);
					return rb.rollback("只能选择自己的下级");
				}
			}

			if (!params.containsKey("price")) {
				log.error("[{}]-扣费金额不能为空", tradeId);
				return rb.rollback("扣费金额不能为空");
			}

			BigDecimal price = DataUtil.getBigDecimal(params.get("price"));
			if (price.compareTo(BigDecimal.ZERO) <= 0) {
				return rb.error("扣费金额不能小于等于0");
			}

			if (!params.containsKey("remark")) {
				params.put("remark", "手动扣费");
			}
			params.put("userId", userId);
			params.put("parentUserId", parentId);
			log.info("[{}]-插入账单明细", tradeId);
			rb.run(saveTransactionFlow(tradeId, params));
			if (!rb.isSuccess()) {
				return rb;
			}
			log.info("[{}]-扣除用户余额，插入用户余额明细", tradeId);
			rb.run(saveBalanceDetail(tradeId, rb.get("tf", String.class, Object.class)));
			if (!rb.isSuccess()) {
				return rb;
			}

			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}
	}

	public ReturnBody saveTransactionFlow(String tradeId, Map<String, Object> rd) {
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> params = new HashMap<>();
		params.put("userId", rd.get("userId"));
		params.put("parentUserId", rd.get("parentUserId"));
		params.put("amount", rd.get("price"));
		params.put("payAmount", rd.get("price"));
		params.put("amountState", "02");
		params.put("remark", rd.get("remark"));
		params.put("state", "01");
		params.put("type", "manual_deduc");
		int num = transactionMapperM.saveTransactionFlow(params);
		if (num == 0) {
			log.error("[{}]-插入账单-失败", tradeId);
			return rb.rollback();
		}
		params.put("code", CustomUtil.orderCode(3, (long) params.get("id"), (int) params.get("userId")));
		num = transactionMapperM.updateTransactionFlowCode(params);
		if (num == 0) {
			log.error("[{}]-插入账单-失败", tradeId);
			return rb.rollback();
		}
		log.info("[{}]-插入账单[{}]-成功", tradeId, params);
		rb.put("tf", params);
		return rb.success();

	}

	public ReturnBody saveBalanceDetail(String tradeId, Map<String, Object> tf) {
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> params = new HashMap<>();
		params.put("userId", tf.get("userId"));
		params.put("balance", tf.get("amount"));
		params.put("type", "2");
		int num = accountMapper.updateUserBalance(params);
		if (num == 0) {
			log.error("[{}]-更新用户余额-失败", tradeId);
			return rb.rollback();
		}
		params.put("parentUserId", tf.get("parentUserId"));
		params.put("incomeState", "02");
		params.put("type", "manual_deduc");
		params.put("remark", tf.get("remark"));
		params.put("transactionId", tf.get("id"));
		params.put("state", "01");
		num = accountMapper.saveBalanceDetail(params);
		if (num == 0) {
			log.error("[{}]-保存用户余额明细-失败", tradeId);
			return rb.rollback();
		}
		rb.put("bd", params);
		return rb.success();
	}

}
